const {
	app,
	BrowserWindow,
	ipcMain,
	Menu,
	globalShortcut
} = require('electron')
// import updater from "./updater"

const {
	updater
} = require('./update');
//在 Electron 中，只有在 app 模块的 ready 事件被激发后才能创建浏览器窗口

let mainWindow = null
let streamWindow = null
Menu.setApplicationMenu(null)
// 快捷键注册
function registryShortcut() {
	globalShortcut.register('CommandOrControl+J+K', () => {
		// 获取当前窗口
		BrowserWindow.getFocusedWindow().webContents.openDevTools();
	});
}
ipcMain.on("stream-content-change", function(event, payload) {
	console.log("stream-content-change", payload)
	if (streamWindow) {
		streamWindow.webContents.send('stream-content-change', payload);
	}

})
ipcMain.on("stream-create-window", function(event, payload) {

	createStreamerWindow(payload)
})
ipcMain.on("stream-close-window", function(event, payload) {
	closeStreamWindow()
})

app.on('window-all-closed', function() {
	if (process.platform !== 'darwin') {
		app.quit()
	}
})

app.on('ready', () => {
	updater()
	//创建一个窗口
	mainWindow = new BrowserWindow({
		width: 414,
		height: 700,
		center: true,
		title: "记分工具人",
		webPreferences: {
			nodeIntegration: true,
			enableRemoteModule: true,
			contextIsolation: false,
			touchEvents: true,
			webSecurity: false

		}
	})
	//窗口加载html文件
	mainWindow.loadFile('build/index.html')
	// mainWindow.loadFile('http://localhost:8080/#/')
	mainWindow.on('closed', () => {
		mainWindow = null
		if (process.platform !== 'darwin') {
			app.quit()
		}
	})

})

app.whenReady().then(() => {
	// 注册快捷键
	// if (!isDevelopment) {
	registryShortcut();
	// }
});

function closeStreamWindow() {
	if (streamWindow) {
		streamWindow.close()
	}
}

function createStreamerWindow(payload) {
	if (streamWindow != null) {
		return
	}
	streamWindow = new BrowserWindow({
		// parent: mainWindow,
		width: 414,
		height: 700,
		transparent: true,
		frame: false,
		show: false,
		resizable: true,
		title: "记分工具人",
		// titleBarStyle: 'hidden',
		// titleBarOverlay: true,
		webPreferences: {
			nodeIntegration: true,
			enableRemoteModule: true,
			contextIsolation: false,
			webSecurity: false

		}
	})
	const parentBounds = mainWindow.getBounds();
	const newX = parentBounds.x + parentBounds.width;
	const newY = parentBounds.y;

	// 设置新窗口的位置
	streamWindow.setPosition(newX, newY);
	//窗口加载html文件
	streamWindow.loadFile('stream/stream.html')
	streamWindow.on('closed', () => {
		streamWindow = null
	})
	const {
		webContents
	} = streamWindow;
	webContents.on('did-finish-load', () => {
		streamWindow.show();
		streamWindow.webContents.send('stream-content-change', payload);

	});
}